/*
 * Copyright © 2022 XXXXXXXXX
 * @Author: zhangxiang
 * @Date: 2022-07-19 09:42:10
 * @LastEditors: zhangxiang
 * @LastEditTime: 2023-02-24 09:24:04
 * @Description:
 *
 */

import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/register'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title, to.meta.menuNameKey)

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login' || to.path === 'register') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
    } else {
      // 菜单名同步
      const hasMenuName =
        store.getters.menuName &&
        Object.keys(store.getters.menuName).length > 0
      if (!hasMenuName) {
        store.dispatch('app/syncMenuNames')
      }
      // determine whether the user has obtained his page permission
      const hasPagePermission = store.getters.pagePermissions
      if (hasPagePermission) {
        next()
      } else {
        try {
          // get user info
          const { pagePermissions } = await store.dispatch('user/getUserInfo')

          // generate accessible routes map based on menus
          const accessRoutes = await store.dispatch(
            'permission/generateRoutes',
            pagePermissions
          )

          // dynamically add accessible routes
          router.addRoutes(accessRoutes)

          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next({ ...to, replace: true })
        } catch (error) {
          console.log(error)
          // remove token and go to login page to re-login
          // Message.error({
          //   message: error.message || '获取页面权限失败 请重新登录后重试',
          //   duration: 1500
          // })
          await store.dispatch('user/resetState')
          if (!(error && error.response && error.response.status === 401)) {
            // 非401异常需要重新登录、401异常已在request.js中处理
            next({ path: `/login?redirect=${to.path}`, query: to.query })
          }
          NProgress.done()
        }
      }
    }
  } else {
    /* has no cookie user unlogin */

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next({ path: `/login?redirect=${to.path}`, query: to.query })
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
